package org.upfrost.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.Properties;

public class SectionFileProperties extends Properties
{

	static public SectionFileProperties unsafeRead(Class scope, String filename)
	{
		try {
			return read(scope,filename);
		}
		catch (IOException iox)
		{
			iox.printStackTrace();
		}
		return null;
	}
	
	static public SectionFileProperties read(Class scope, String filename) throws IOException
	{
		InputStream in = scope.getResourceAsStream(filename);
		InputStreamReader isr = new InputStreamReader(in);
		SectionFileProperties result = read(isr);
		isr.close();
		in.close();
		return result;
	}
	
	/**
	 * 
	 * @param input
	 * @return
	 * @throws IOException 
	 * @TODO handle escaped and quoted text
	 */
	
	static public SectionFileProperties read(Reader input) throws IOException
	{
		LineNumberReader lnr = new LineNumberReader(input);
		String line;
		String section = null;
		StringBuffer buffer = new StringBuffer();
		
		SectionFileProperties result = new SectionFileProperties();
		
		while ((line=lnr.readLine()) != null)
		{
			// First, remove comments 
			if (line.trim().startsWith(";"))
				line = "";
//			int comment = line.indexOf(';');
//			if (comment >= 0)
//				line = line.substring(0,comment);
			
			if (line.length()>0 && line.startsWith("["))
			{
				// flush whatever section already started
				if (section != null)
				{
					result.put(section.trim(), buffer.toString());
					buffer.setLength(0);
				}
				
				int end = line.indexOf(']');
				if (end >= 0)
					section = line.substring(1, end);
				else
					section = line.substring(1);
			}
			else
			{
				buffer.append(line + "\n");
			}
		}
		if (section != null)
			result.put(section, buffer.toString());
		
		return result;
	}
	
}
